package io.geekidea.boot.util.dingtalk;

import cn.hutool.http.HttpStatus;
import com.aliyun.dingtalkstorage_1_0.models.SubscribeEventResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.open.app.api.GenericEventListener;
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import lombok.extern.slf4j.Slf4j;
import shade.com.alibaba.fastjson2.JSONObject;

@Slf4j
public class EventUtil {

  /**
   * 使用 Token 初始化账号Client
   *
   * @return Client
   * @throws Exception
   */
  public static com.aliyun.dingtalkstorage_1_0.Client createStorageClient() throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
    config.protocol = "https";
    config.regionId = "central";
    return new com.aliyun.dingtalkstorage_1_0.Client(config);
  }

  public static boolean folderEventSubscribe(String accessToken, String unionId, String spaceId) {
    com.aliyun.dingtalkstorage_1_0.Client client = null;
    try {
      client = createStorageClient();
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
      return false;
    }

    com.aliyun.dingtalkstorage_1_0.models.SubscribeEventHeaders subscribeEventHeaders = new com.aliyun.dingtalkstorage_1_0.models.SubscribeEventHeaders();
    subscribeEventHeaders.xAcsDingtalkAccessToken = accessToken;
    com.aliyun.dingtalkstorage_1_0.models.SubscribeEventRequest subscribeEventRequest = new com.aliyun.dingtalkstorage_1_0.models.SubscribeEventRequest()
        .setUnionId(unionId)
        .setScopeId(spaceId)
        .setScope("SPACE");
    try {
      SubscribeEventResponse resp = client.subscribeEventWithOptions(
          subscribeEventRequest, subscribeEventHeaders,
          new RuntimeOptions());
      if (resp.getStatusCode() == HttpStatus.HTTP_OK) {
        return resp.getBody().getSuccess();
      }
    } catch (Exception e) {
      log.error("错误消息：{}", e.getMessage(), e);
    }
    return false;
  }

}
